
let useExt = require('../utils/glext');

class Application{

    /**
     *
     * @param store {Store}
     */
    constructor(width = 800,height = 600) {
        this.width = width;
        this.height = height;
        this.canvas = document.createElement('canvas');
        this.canvas.classList.add('canvas');
        document.body.appendChild(this.canvas);

        this.canvas.width   = width;
        this.canvas.height  = height;

        this._last = Date.now();
        let gl = this._gl = this.canvas.getContext('webgl');

        useExt(gl, 'OES_vertex_array_object');
        useExt(gl, 'ANGLE_instanced_arrays');
        useExt(gl,'WEBGL_depth_texture');
        this._initGL();

        this.scene = null;
    }

    startScene(scene){
        this.scene = scene;
        this.scene.init();
        this._loop();
    }


    _initGL(){
        let gl = this._gl;
        gl.enable(gl.DEPTH_TEST);
        gl.frontFace(gl.CCW);
        gl.cullFace(gl.BACK);
        gl.enable(gl.CULL_FACE);
        gl.clearColor(0,0,0,1);
        gl.viewport(0,0,this.width,this.height);

        // 对纹理坐标进行反转
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);

        // 紧密包装数据格式,一次一个
        // TODO:可以进行优化
        gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
    }

    _loop(){
        requestAnimationFrame(this._loop.bind(this));

        let now = Date.now();
        let dt = now - this._last;
        this._last = now;

        this._update(dt);
        this._render();
    }

    _update(dt){
        if (this.scene){
            this.scene.update(dt);
        }
    }
    _render(){
        let gl = this._gl;
        gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT);
        if (this.scene){
            this.scene.render();
        }
    }

    getGL(){
        return this._gl;
    }
}

module.exports = Application;
